//
//  TradeDetailView.m
//  DaDaBao
//
//  Created by admin on 15/8/26.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "TradeRecordView.h"
#import "TradeModel.h"
@interface TradeRecordView()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)NSMutableArray *listDataArray;
@property (nonatomic,assign)int idx;
@property (nonatomic,strong)NSString *url;
@property (strong, nonatomic)UIView *noDataView;

@property(nonatomic,strong)UIView *noNet;
@property (nonatomic,assign) int n;
@property(nonatomic,assign)float cellheight;
@end
@implementation TradeRecordView
- (void)getHttpData
{
   
    _noDataView.hidden = TRUE;
    _noNet.hidden = TRUE;
    _n++;

    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"token"]) {
        NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1], @"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]};
        [AppGlobalClass PostDataWithNSstring:self.url withDictionary:dict success:^(NSDictionary *dictionary){
            if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
            {
                [_recordTableView.header endRefreshing];
                [_recordTableView.footer setState:MJRefreshStateIdle];
                [_recordTableView.footer endRefreshing];
                
                if(_idx == 0)
                {
                    [_listDataArray removeAllObjects];
                }
                
                NSArray *dataArray = [dictionary objectForKey:@"responseData"];
                NSDictionary *dataDict = [dataArray objectAtIndex:0];
                
                if([[dataDict objectForKey:@"pages"] intValue] > _idx)
                {
                    NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                    
                    for(int i = 0; i < listArray.count; i++)
                    {
                        TradeModel *model = [[TradeModel alloc]initWithDictionary:[listArray objectAtIndex:i]];
                        [_listDataArray addObject:model];
                    }
                    
                    _idx++;
                    
                    if(listArray.count < 10)
                    {
                        [_recordTableView.footer endRefreshingWithNoMoreData];
                    }
                    else {
                        if (_n<2) {
                            _recordTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        }
                        
                    }
                    [_recordTableView reloadData];
                    
                }
                else
                {
                    if (self.listDataArray.count==0) {
                        _noDataView.hidden = FALSE;
                        
                    }
                    
                    [self.recordTableView.footer endRefreshingWithNoMoreData];
                }
            }
            else
            {
                ALERT_VIEW([dictionary objectForKey:@"message"]);
            }

            [self.recordTableView.header endRefreshing];

        } failure:^(NSError *error){
            
            _noDataView.hidden = FALSE;
            [_listDataArray removeAllObjects];
            [_recordTableView reloadData];
            
            [_recordTableView.header endRefreshing];
            [_recordTableView.footer setState:MJRefreshStateIdle];
            [_recordTableView.footer endRefreshing];
            
        } networkerror:^(NSString *networkerror){
            
            [self.listDataArray removeAllObjects];
            [self.recordTableView reloadData];
            
            [_recordTableView.header endRefreshing];
            [_recordTableView.footer setState:MJRefreshStateIdle];
            [_recordTableView.footer endRefreshing];
            
            _noNet.hidden = FALSE;
            
        }];

    }
        
}
//没网提示
#pragma mark - 没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noNet.center = CGPointMake(_recordTableView.center.x, _recordTableView.center.y - 64 - 32);
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"网络不通\n点击重新搜索";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
    }
    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noDataView.center =CGPointMake(_recordTableView.center.x, _recordTableView.center.y - 64 - 32);
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"暂无数据\n点击重新搜索";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
    }
    
    return _noDataView;
}- (void)noResultButtonAction:(UIButton *)btn{
    [self.recordTableView.header beginRefreshing];
}

- (void)buttonAgainTapped:(id)sender
{
    [_recordTableView.header beginRefreshing];
}

-(id)initWithFrame:(CGRect)frame withUrl:(NSString *)url nameWithArray:(NSArray *)arr
{
    if (self = [super initWithFrame:frame])
    {
        _url = url;
        _listDataArray = [[NSMutableArray alloc]init];
        //创建表头目录
        UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40*HSCALE)];
        headView.backgroundColor = [UIColor hexStringToColor:kColorBackground];
        [self addSubview:headView];
        
        UILabel * userLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        userLabel.center = CGPointMake(SCREEN_WIDTH/6, 20*HSCALE);
        userLabel.text = [arr objectAtIndex:0];
        userLabel.textAlignment = NSTextAlignmentCenter;
        [headView addSubview:userLabel];
        
        UILabel * investMoneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        investMoneyLabel.center = CGPointMake(SCREEN_WIDTH/2, 20*HSCALE);
        investMoneyLabel.text =[arr objectAtIndex:1];
        investMoneyLabel.textAlignment = NSTextAlignmentCenter;
        [headView addSubview:investMoneyLabel];
        
        UILabel * investTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        investTimeLabel.center = CGPointMake(SCREEN_WIDTH*5/6, 20*HSCALE);
        investTimeLabel.text = [arr objectAtIndex:2];;
        investTimeLabel.textAlignment = NSTextAlignmentCenter;
        [headView addSubview:investTimeLabel];
        
        //创建表
        _recordTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40*HSCALE, SCREEN_WIDTH, SCREEN_HEIGHT  - 40*HSCALE) style:UITableViewStylePlain];
        _recordTableView.delegate = self;
        _recordTableView.dataSource = self;
        if ([ _recordTableView respondsToSelector:@selector(setSeparatorInset:)]) {
            
            [_recordTableView   setSeparatorInset:UIEdgeInsetsZero];
            
        }
        
        if ([_recordTableView respondsToSelector:@selector(setLayoutMargins:)]) {
            
            [_recordTableView setLayoutMargins:UIEdgeInsetsZero];
            
        }
//        _recordTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        __weak __typeof(self) weakSelf = self;
        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        _recordTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshTheTableView];
        }];
        
        [_recordTableView.header beginRefreshing];//开始刷新
        _recordTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];//设置当数据不多的时候，下面无cell
        [self addSubview:_recordTableView];
        
        [_recordTableView addSubview:self.noDataView];
        [_recordTableView addSubview:self.noNet];
    }
    return self;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_listDataArray count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        TradeModel *model  = _listDataArray[indexPath.row];

        if (_listDataArray.count>0) {
            float height = [UILabel height:model.paname widthOfFatherView:SCREEN_WIDTH/3 textFont:[UIFont systemFontOfSize:15.0f]];
            float height1 = [UILabel height:[NSString stringWithFormat:@"%@元",model.orderMoney] widthOfFatherView:SCREEN_WIDTH/3 textFont:[UIFont systemFontOfSize:15.0f]];
            

            if (height > 50.0f ) {
                    return height;
                }
                else if(height1>50.0f)
                {
                    return height1;
                }
            
            else
            {
                return 50.0f;
  
            }
        }
        else
        {
            return 50.0f;
        }
        
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:FALSE];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellID = @"a";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        
        UILabel * projName = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 50)];
        projName.center = CGPointMake(SCREEN_WIDTH/6, 25);
        projName.textAlignment = NSTextAlignmentCenter;
        projName.tag = 100;
        projName.numberOfLines = 0;
        projName.font = [UIFont systemFontOfSize:15.0f];
        projName.textColor = [UIColor hexStringToColor:kColorGray];
        [cell.contentView addSubview:projName];
        
        UILabel * investMoneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 50)];
        investMoneyLabel.center = CGPointMake(SCREEN_WIDTH/2, 25);
        investMoneyLabel.textAlignment = NSTextAlignmentCenter;
        investMoneyLabel.tag = 101;
        investMoneyLabel.numberOfLines = 0;

        investMoneyLabel.font = [UIFont systemFontOfSize:15.0f];

        investMoneyLabel.textColor = [UIColor hexStringToColor:kColorGray];

        [cell.contentView addSubview:investMoneyLabel];
        
        UILabel * investTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 50)];
        investTimeLabel.numberOfLines = 0;
        investTimeLabel.center = CGPointMake(SCREEN_WIDTH*5/6 - 10.0f, 25);
        investTimeLabel.textAlignment = NSTextAlignmentRight;
        investTimeLabel.tag = 102;
        investTimeLabel.font = [UIFont systemFontOfSize:15.0f];

        investTimeLabel.textColor = [UIColor hexStringToColor:kColorGray];

        [cell.contentView addSubview:investTimeLabel];
        
//        UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(8.0f, 49.5f, SCREEN_WIDTH-16.0f, 0.5f)];
//        sepLab.backgroundColor = [UIColor hexStringToColor:kColorGraySperator];
//        [cell addSubview:sepLab];
        
    }
    
    TradeModel *model = [_listDataArray objectAtIndex:indexPath.row];
    
    UILabel * projName = (UILabel *)[cell.contentView viewWithTag:100];
    //    赋值
    projName.text = model.paname;
    float pheight = [UILabel height:model.paname widthOfFatherView:projName.frame.size.width textFont:projName.font];
    projName.frame =CGRectMake(0, 0, SCREEN_WIDTH/3, pheight);
    projName.center = CGPointMake(SCREEN_WIDTH/6, 25);
    UILabel * investMoneyLabel = (UILabel *)[cell.contentView viewWithTag:101];
    //   赋值
    investMoneyLabel.text = [NSString stringWithFormat:@"%@元",model.orderMoney];
    float mheight = [UILabel height:investMoneyLabel.text widthOfFatherView:investMoneyLabel.frame.size.width textFont:investMoneyLabel.font];
   investMoneyLabel.frame = CGRectMake(0, 0, SCREEN_WIDTH/3, mheight);
    investMoneyLabel.center = CGPointMake(SCREEN_WIDTH/2, 25);


    UILabel * investTimeLabel = (UILabel *)[cell.contentView viewWithTag:102];
    //   赋值
    investTimeLabel.text = model.modifyTime;
    return cell;
}
-(void)refreshTheTableView
{
    _idx = 0;
    _n = 0;
    [self getHttpData];
}

//加载更多数据
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
